package com.cloudsigns.factorymanager2.engineering.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudsigns.factorymanager2.R;
import com.cloudsigns.factorymanager2.cusenum.CommonEnum;
import com.cloudsigns.factorymanager2.engineering.IView.InSendPatrolOrderView;
import com.cloudsigns.factorymanager2.engineering.adapter.AddPublicationOrderAdapter;
import com.cloudsigns.factorymanager2.engineering.bean.DispatchPatrolBean;
import com.cloudsigns.factorymanager2.engineering.bean.Dispatchbean;
import com.cloudsigns.factorymanager2.engineering.bean.MediaBean;
import com.cloudsigns.factorymanager2.engineering.bean.PatrolOrderBean;
import com.cloudsigns.factorymanager2.engineering.presenter.EngineeringUserListPresenter;
import com.cloudsigns.factorymanager2.engineering.presenter.SendPatrolOrderPresenter;
import com.cloudsigns.factorymanager2.project.myinerface.ItemRemoveListener;
import com.cloudsigns.factorymanager2.project.utils.ConstantUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tony on 2018/5/19.
 */

public class DispatchPatrolOrderDetailActivity extends Activity implements View.OnClickListener, InSendPatrolOrderView, ItemRemoveListener {
    private View rl_back;
    private TextView tv_title;
    private TextView tv_project_name, tv_engineering_name;
    private ScrollView scrollview;
    private LinearLayout ll_region;
    private View rl_add_product;
    private ImageView img_point_locationt;
    private TextView btn_dispatch_order, btn_delete_order;
    private LayoutInflater layoutInflater;
    private ArrayList<MediaBean> mediaBeanList;
    /*保存该页面点位集合中未=指定分派人的 点位id集合*/
    private List<String> mediaIdList = new ArrayList<>();
    private String receiveAccountId;
    private HashMap<String, List<MediaBean>> areaNameMap = new HashMap<>();
    //    private List<String> selectedItemList = new ArrayList<String>();
    private PatrolOrderBean patrolOrderBean;
    private String orderId;
    private String TAG = DispatchPatrolOrderDetailActivity.class.getSimpleName();
    private SendPatrolOrderPresenter sendPatrolOrderPresenter;
    private CommonEnum.AssignStatus assignStatus;
    private String mediaId;
    private boolean isDispatch, isDelete, isAddMedia;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        // 沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    );
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        setContentView(R.layout.layout_dispatch_patrol_order_detail);

        layoutInflater = getLayoutInflater();
        sendPatrolOrderPresenter = new SendPatrolOrderPresenter(this);
        init();
        if (null != getIntent()) {
            mediaBeanList = (ArrayList<MediaBean>) getIntent().getSerializableExtra(ConstantUtil.KEY_1);
            patrolOrderBean = (PatrolOrderBean) getIntent().getSerializableExtra(ConstantUtil.KEY_2);

            if (null != mediaBeanList && mediaBeanList.size() > 0) {
                MediaBean mediaBean = mediaBeanList.get(0);

                assignStatus = mediaBean.getAssignStatus();
                mediaId = mediaBean.getId();

                receiveAccountId = mediaBean.getAssignReceiveAccountId();
//            tv_project_name.setText(mediaBean.getRegionName());
                tv_project_name.setText("内派");
                if (!TextUtils.isEmpty(mediaBean.getAssignReceiveAccountName()))
                    tv_engineering_name.setText("/" + mediaBean.getAssignReceiveAccountName());

                orderId = getIntent().getStringExtra("orderId");


                if (null != assignStatus) {
                    if (assignStatus == CommonEnum.AssignStatus.CREATED) {
                        btnClickable(true, true, true);
                    } else if (assignStatus == CommonEnum.AssignStatus.EDITED) {
                        btnClickable(true, true, true);
                    } else if (assignStatus == CommonEnum.AssignStatus.SEND) {
                        btnClickable(false, false, false);

                    } else if (assignStatus == CommonEnum.AssignStatus.RECEIVED) {
                        btnClickable(false, false, false);
                    } else if (assignStatus == CommonEnum.AssignStatus.RETURNED) {
                        btnClickable(false, false, false);

                    } else if (assignStatus == CommonEnum.AssignStatus.COMPLETED) {
                        btnClickable(false, false, false);
                    } else {
                        btnClickable(true, false, false);
                    }
                }
            }

            initData();
        }
    }

    private void init() {
        rl_back = findViewById(R.id.rl_back);
        tv_title = findViewById(R.id.tv_title);
        tv_project_name = findViewById(R.id.tv_project_name);
        tv_engineering_name = findViewById(R.id.tv_engineering_name);
        rl_add_product = findViewById(R.id.rl_add_product);
        img_point_locationt = findViewById(R.id.img_point_locationt);
        scrollview = findViewById(R.id.scrollview);
        ll_region = findViewById(R.id.ll_region);
        rl_add_product = findViewById(R.id.rl_add_product);
        btn_dispatch_order = findViewById(R.id.btn_dispatch_order);
        btn_delete_order = findViewById(R.id.btn_delete_order);

        tv_title.setText("分派信息");
        rl_add_product.setOnClickListener(this);
        rl_back.setOnClickListener(this);
        btn_dispatch_order.setOnClickListener(this);
        btn_delete_order.setOnClickListener(this);
    }

    private void initData() {
        areaNameMap.clear();


        for (int i = 0; i < mediaBeanList.size(); i++) {
            MediaBean mediaBean = mediaBeanList.get(i);
            if (mediaBean.isChecked() && !mediaBean.isSend() && !mediaIdList.contains(mediaBean.getId())) {
                mediaIdList.add(mediaBean.getId());
            }

            String areaName = mediaBean.getAreaName();
            if (areaNameMap.containsKey(areaName)) {
                areaNameMap.get(areaName).add(mediaBean);
            } else {
                ArrayList<MediaBean> mediaBeanArrayList = new ArrayList<>();
                mediaBeanArrayList.add(mediaBean);
                areaNameMap.put(areaName, mediaBeanArrayList);
            }
        }

        updateUi();
    }


    private void updateUi() {
        if (null != areaNameMap && null != ll_region) {
            ll_region.removeAllViews();

            for (Map.Entry<String, List<MediaBean>> entry : areaNameMap.entrySet()) {
                View view = layoutInflater.inflate(R.layout.layout_point_location_content, null);
                TextView tv_area_name = view.findViewById(R.id.tv_area_name);
                tv_area_name.setText(entry.getKey());

                ListView lv_media = view.findViewById(R.id.lv_media);

                List<MediaBean> mediaRegionBeanList = entry.getValue();
                AddPublicationOrderAdapter adapter = new AddPublicationOrderAdapter(this, TAG);
//                PointLocationAdapter adapter = new PointLocationAdapter(this, TAG);
                adapter.setData(mediaRegionBeanList);
                adapter.setItemRemoveListener(this);
                lv_media.setAdapter(adapter);
                view.setTag(mediaRegionBeanList);


                ll_region.addView(view);


            }
        }

        scrollview.smoothScrollTo(0, 0);

    }

    private void btnClickable(boolean isDispatch, boolean isDelete, boolean isAddMedia) {
        this.isDispatch = isDispatch;
        this.isDelete = isDelete;
        this.isAddMedia = isAddMedia;

        if (isAddMedia) {
            img_point_locationt.setVisibility(View.VISIBLE);
        } else {
            img_point_locationt.setVisibility(View.GONE);
        }

        if (isDispatch) {
            btn_dispatch_order.setBackgroundResource(R.color.btn_bg_color_00B050);
            btn_dispatch_order.setTextColor(getResources().getColor(R.color.rgb_ffffffff));
        } else {
            btn_dispatch_order.setBackgroundResource(R.mipmap.btn_bg_short_gray);
            btn_dispatch_order.setTextColor(getResources().getColor(R.color.rgb_ffffffff));
        }

        if (isDelete) {
            btn_delete_order.setBackgroundResource(R.color.btn_bg_color_C00000);
            btn_delete_order.setTextColor(getResources().getColor(R.color.rgb_ffffffff));
        } else {
            btn_delete_order.setBackgroundResource(R.mipmap.btn_bg_short_gray);
            btn_delete_order.setTextColor(getResources().getColor(R.color.rgb_ffffffff));
        }
    }

    ;

    private void dispatchOrder() {
        sendPatrolOrderPresenter.sendPatrolOrder();
    }

    private void deleteOrder() {
        Intent mIntent = new Intent();
        mIntent.putExtra(ConstantUtil.KEY_2, true);
        setResult(RESULT_OK, mIntent);
        Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    public void onClick(View view) {
        Intent mIntent;
        switch (view.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.rl_add_product:
                if (isAddMedia) {
                    mIntent = new Intent(DispatchPatrolOrderDetailActivity.this, SelectMediaForManagerActivity.class);
//                    mIntent.putExtra(ConstantUtil.KEY_1, (Serializable) mediaBeanList);
                    mIntent.putExtra(ConstantUtil.KEY_2, patrolOrderBean);


//                    mIntent.putExtra(ConstantUtil.KEY_1, (Serializable) selectedItemList);
//                    mIntent.putExtra(ConstantUtil.KEY_2, patrolOrderBean);
                    mIntent.putExtra("tag", TAG);
                    startActivityForResult(mIntent, ConstantUtil.START_ACTIVITY_KEY_1);
                }

                break;
            case R.id.btn_dispatch_order:
                if (isDispatch)
                    dispatchOrder();
                break;
            case R.id.btn_delete_order:
                if (isDelete)
                    deleteOrder();
                break;

        }
    }


    @Override
    public void remove(int positon) {

    }


    @Override
    public void remove(View view) {
        /*position 在页面列表中的位置   lvPosition  在订单 点位数据集合中的位置 */
        int positon = (int) view.getTag();
        if (positon >= 0 && positon < mediaBeanList.size()) {
            MediaBean mediaBean = mediaBeanList.get(positon);
            mediaBean.setChecked(false);
            mediaBean.setSend(false);
            if (mediaIdList.contains(mediaBean.getId()))
                mediaIdList.remove(mediaBean.getId());

            int lvPosition = mediaBean.getLvPosition();
            if (lvPosition >= 0 && lvPosition < patrolOrderBean.getMediaList().size()) {
                patrolOrderBean.getMediaList().set(lvPosition, mediaBean);
            }

            mediaBeanList.remove(positon);
            initData();
        }


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case ConstantUtil.START_ACTIVITY_KEY_1:
                if (data != null) {
                    patrolOrderBean = (PatrolOrderBean) data.getSerializableExtra(ConstantUtil.KEY_1);
                    List<MediaBean> mediaBeanLs = patrolOrderBean.getMediaList();
                    if (null != mediaBeanLs) {
                        for (MediaBean mediaBean : mediaBeanLs) {
                            if (mediaBean.isChecked() && !mediaBean.isSend()) {
                                if (!mediaIdList.contains(mediaBean.getId())) {
                                    mediaBeanList.add(mediaBean);
                                }

                            }
                        }
                    }

                    initData();

                }
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public String getId() {
        return orderId;
    }

    @Override
    public List<DispatchPatrolBean> getEngineeringPatrolOrderSendItemRequestList() {

        List<DispatchPatrolBean> dispatchPatrolBeanList = new ArrayList<>();
        if (null != areaNameMap) {
            for (Map.Entry<String, List<MediaBean>> entry : areaNameMap.entrySet()) {
                List<MediaBean> mediaRegionBeanList = entry.getValue();
                if (null != mediaRegionBeanList) {
                    for (MediaBean mediaBean : mediaRegionBeanList) {
                        DispatchPatrolBean dispatchPatrolBean = new DispatchPatrolBean();
                        dispatchPatrolBean.setMediaId(mediaBean.getId());
//                        dispatchPatrolBean.setMediaId(mediaBean.getNumber());
//                        dispatchPatrolBean.setMediaId(mediaBean.getId());
                        dispatchPatrolBean.setReceiveAccountId(receiveAccountId);
                        dispatchPatrolBeanList.add(dispatchPatrolBean);
                    }
                }
            }
        }
        return dispatchPatrolBeanList;
    }

    @Override
    public void sendPatrolOrderSuccess() {
        Toast.makeText(this, "派发成功", Toast.LENGTH_SHORT).show();
        Intent mIntent = new Intent();
        mIntent.putExtra(ConstantUtil.KEY_1, true);
        setResult(RESULT_OK, mIntent);
        finish();
    }

    @Override
    public void sendPatrolOrderFailed(String desc) {
        Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }


}
